var c = document.getElementById("canvas") as HTMLCanvasElement;
var context = c.getContext("2d") as CanvasRenderingContext2D; //获取canvas上下文
var w = (c.width = window.innerWidth);
var h = (c.height = window.innerHeight); //设置canvas宽、高
const balls: Balls[] = [];

function getRandomColor() {
  const r = `#${Math.random().toString(16).slice(2, 8)}`;
  return r;
}

class Balls {
  x: number;
  y: number;
  r: number;
  color: string = getRandomColor();
  dx: number = parseInt((Math.random() * 10 - 5).toString());//确保能够正负方向运动
  dy: number = parseInt((Math.random() * 10 -5).toString());
  sub: number;
  constructor(x: number, y: number, r: number, sub: number) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.sub = sub;
    balls.push(this);
  }
  draw() {
    context.beginPath();
    context.arc(this.x, this.y, this.r, 0, Math.PI * 2);
    context.fillStyle = this.color;
    context.fill();
  }
  move() {
    this.r -= this.sub;
    this.x += this.dx;
    this.y += this.dy;
    if (this.r <= 0) {
      this.remove();
    }
  }
  remove() {
    for (let i = 0; i < balls.length; i++) {
      if (balls[i] === this) {
        balls.splice(i, 1);
      }
    }
  }
}

// 给画布添加鼠标移动事件
c.addEventListener("mousemove", function (e) {
  new Balls(e.offsetX, e.offsetY, 30, 0.5);
});

function animate() {
  context.clearRect(0, 0, w, h);
  for (let i = 0; i < balls.length; i++) {
    balls[i].move();
    if (balls[i]) {
        balls[i].draw()
    }

}
  requestAnimationFrame(animate);
}
animate();
